<template>
 <el-row :class="tabType + '_conbox'">
    <el-col :span="expandLayout ? 8 : 14">
      <div class="chat_msg_box">
        <webchat-con-chat-head
          :showGrabIcon="showGrabIcon"
          :isVideoing="isVideoing"
          :videoSessionid="videoSessionid"
          @VideoTips="showVideoTipsDialog"
        ></webchat-con-chat-head>
        <webchat-con-msg-box
          :chatMsgCon="chatMsgCon"
          :uploaded="uploaded"
          :expandLayout="expandLayout"
          :initiativeSession="(tabType === 'webchat_all' || tabType === 'webchat_laterProcess' || tabType === 'webchat_robot') && chatInfo.status === 'finish' ? true : false"
          @videoReplay="videoReplay1"
        ></webchat-con-msg-box>
        <send-chat-msg-box v-if="urlTabType === 'webchat_todo'"
          :sendChatMsg="sendChatMsg"
          :webchatUserHistory="webchatUserHistory"
          :iframeMsgUrl="iframeMsgUrl"
          :uploaded="uploaded"
          :chatMsgCon="chatMsgCon"
          :expandLayout="expandLayout"
          @VideoTips="showVideoTipsDialog"
          @customerAddBlack="customerAddBlack"
          @startVideoChat="startVideoChat"
          @startShareScreen="startShareScreen"
        >
        </send-chat-msg-box>
        <!-- <div :style="{width: expandLayout ? '33.33333%' : '58.3333%'}" v-if="tabType === 'webchat_all' && chatInfo.status === 'finish'" class="initiativeSession"> -->
        <div :style="{width: '100%'}" v-if="tabType === 'webchat_all' && chatInfo.status === 'finish'" class="initiativeSession">
          <div class="initiative-warp"></div>
          <el-button class="initiative-btn primary_btn" type="primary" @click="initiatingWebchat">{{initiatingSessionBtn}}</el-button>
        </div>
      </div>
    </el-col>
    <el-col :span="expandLayout ? 16 : 10" style="height: 300px; z-index: 2999" v-if="!renderCustomer" v-loading="!renderCustomer"></el-col>
    <el-col :span="expandLayout ? 16 : 10" v-if="renderCustomer">
      <webchat-con-chat-info
        :webchatData="webchatData"
        :chatInfo="chatInfo"
        :customer="customer"
        :currentBusinessObj="currentBusinessObj"
        @toggleExpandLayout="handleExpandLayout"
      ></webchat-con-chat-info>
    </el-col>
    <el-dialog :close-on-click-modal="false"  :title="$t('videoChat.operaTip')" :visible.sync="VideoTipsDialog" :modal="false" custom-class="VideoTips" size="tiny">
      <p class="tipsword">{{VideoActionTips}}</p>
      <div class="tipsbutton">
        <el-button type="primary" class="primary_btn" @click="VideoTipsDialog = false">{{$t('public.confirm')}}</el-button>
      </div>
    </el-dialog>
    <invite-conversation v-if="inviteCon" :inviteType="'invite'" :inviteConData="inviteConData" @closeInvite="cancelInviteSession"></invite-conversation>
    <video-replay v-if="playVideoReplay" :replayUrl="videoReplayUrl" :chatMsg="videoReplatChatMsg" @closeVideoReplay="closeVideoReplay"></video-replay>
  </el-row>
</template>
<script>
  import videoReplay from '@/components/public-modules/popups/PopDragVideoReplay.vue'
  // import BigImage from '@/components/public-modules/popups/PopDragBigImage.vue'
  import { isEmpty } from 'lodash'
  import * as gtypes from '@/store/mutation-types'
  import * as types from '@/store/modules/webchat/mutation-types'
  import { deepClone, contains, getCache, initFinishName } from '@/utils/m7Utils'
  import * as webchatUtils from '@/utils/webchat.js'
  import InviteConversation from '@/components/public-modules/InviteConversation/InviteConversation.vue'
  import WebchatConMsgBox from '../webchat/WebchatConMsgBoxNew.vue'
  import WebchatConChatHead from '../webchat/WebchatConChatHead.vue'
  import WebchatConChatInfo from '../webchat/WebchatConChatInfo.vue'
  import sendChatMsgBox from '../webchat/WebchatConSendMsg.vue'
  import bus from '@/store/eventBus'
  export default {
    name: 'WebChatSummary',
    data () {
      return {
        // tabType: 'webchat_todo',
        customerId: '',
        loading: false,
        cardLoading: true, // 从卡片点击到右边的时候的加载
        sessionId: '',
        sid: '',
        webchatBigImage: false, // 是否查看大图
        bigImgUrl: '',      // 当前大图地址
        videoReplayUrl: '', // 视频聊天记录播放地址
        playVideoReplay: false, // 是否播放视频聊天记录
        videoReplatChatMsg: '', // 当前播放的视频聊天信息
        finishOptions: {},
        imageUrls: [], // 聊天记录里的图片地址数组
        chatHead: {
          dialogTableVisible: false,
          endOptionsUl: [],
          endSessionActive: [],
          endSessionFlag: false
        },
        chatMsgCon: {
          font: 'font12'
        },
        sendChatMsg: {
          content: ''
        },
        showGrabIcon: false,   // 判断是否展示抢接会话按钮会话的依据
        uploaded: {
          uploadImg: false,
          uploadImgSessionId: '',
          uploadFile: {
            flag: false,
            progress: '',
            name: '',
            uploadFileSessionId: ''
          }
        },
        VideoTipsDialog: false,
        VideoActionTips: '',
        iframeMsgUrl: '',     // iframe消息地址
        renderCustomer: false,  // 异步加载右侧详情组件
        initiatingSessionBtn: this.$t('webchat.initiatingSession'), // 发起主动会话按钮上的文案
        expandLayout: false // 展开布局flag
      }
    },
    provide () {
      return {
        tabsList: [
          {
            name: 'public.shopping',
            tabName: 'shopping',
            type: 'feature',
            size: {
              width: 0,
              height: 0
            }
          },
          {
            name: 'public.customerInfo',
            tabName: 'customerInfo',
            type: 'feature',
            size: {
              width: 0,
              height: 0
            }
          }, {
            name: 'webchat.quickReplay',
            tabName: 'quickReply',
            type: 'feature',
            size: {
              width: 0,
              height: 0
            }
          }, {
            name: 'webchat.auxiliaryAgent',
            tabName: 'auxiliaryAgent',
            type: 'feature',
            size: {
              width: 0,
              height: 0
            }
          }
        ]
      }
    },
    watch: {
      // 如果路由有变化，会再次执行该方法
      // 'refreshWebchatRight': 'routerChange',
      $route (to, from) {
        if (to.path.split('/')[4] !== from.path.split('/')[4] || to.path.split('/')[3] !== from.path.split('/')[3]) {
          this.playVideoReplay = false
        }
        if (to.path.split('/')[2] === 'webchat' &&
          this.cardLoading === false && (to.path.split('/')[3] !== 'webchat_all' ||
            to.path.split('/')[3] !== 'webchat_robot' ||
            to.path.split('/')[3] !== 'webchat_laterProcess')) {
          this.fetchData()
          this.closeBigImage()
        }
        // move from webchatcontainer
        let toArr = to.path.split('/')
        if (toArr[2] === 'webchat')
        this.sendChatMsg.content = ''
        this.chatMsgCon.font = window.localStorage.getItem('imFontCon')
        if (!this.chatMsgCon.font) {
          this.chatMsgCon.font = 'font12'
        }
        if (to.path.split('/').length > 4) {
          if (this.$store.state.webchat.lastContent[to.path.split('/')[4]] !== undefined) {
            this.sendChatMsg.content = this.$store.state.webchat.lastContent[to.path.split('/')[4]]
          }
        }
        let fromArr = from.path.split('/')
        let conbox = document.getElementsByClassName('send_msg_textarea')
        if (conbox.length && fromArr.length > 4) {
          let value = conbox[0].value
          this.$store.commit(types.REMEMBER_LAST_CON, {id: fromArr[4], data: value})
        }
        // move from webchatcontainer end
      },
      customer: {
        handler: function (val, oldVal) {
          if (val !== oldVal && !this.loading) {
            let currCustomer = {}
            if (this.$route.path.split('/')[2] === 'webchat') {
              if (this.tabType === 'webchat_todo' || this.tabType === 'webchat_all' || this.tabType === 'webchat_robot' || this.tabType === 'webchat_laterProcess') {
                currCustomer = this.$store.state.webchat.current[this.tabType].currentCustomer || {}
              }
            }
            this.customerId = currCustomer._id || ''
            let noCustomer = isEmpty(currCustomer)
            if (!noCustomer && this.$route.path.split('/').length > 4) {
              updateCurrentWebchatList(this.$store, this.sid, currCustomer)
            }
          }
        },
        deep: true
      }
    },
    computed: {
      path () {
        return this.$route.path.split('/')
      },
      type () {
        return this.path[2] || ''
      },
      tabType () {
        return this.path[3] || ''
      },
      callId () {
        return this.path[4] || ''
      },
      currentBusinessObj () {
        // 传递给客户模块的业务信息
        let dealSrc = ''
        if (this.tabType === 'webchat_todo') {
          dealSrc = 'ecommercePopupWebchat'
        } else {
          dealSrc = 'ecommerceRelocationWebchat'
        }
        return {dealSrc: dealSrc, callId: this.callId, tabType: this.tabType, type: 'webchat'}
      },
      customer () {
        // todo webchat_todo列表里的定位客户的时候,这里没有执行,原因未知
        let currCustomer = {}
        if (this.$route.path.split('/')[2] === 'webchat') {
          if (this.tabType === 'webchat_todo' || this.tabType === 'webchat_all' || this.tabType === 'webchat_robot' || this.tabType === 'webchat_laterProcess') {
            currCustomer = this.$store.state.webchat.current[this.tabType].currentCustomer || {}
          }
        }
        this.customerId = currCustomer._id || ''
        let noCustomer = isEmpty(currCustomer)
        let phone = ''
        let name = ''
        let person = ''
        if (this.$store.state.webchat.autoCust[this.sessionId]) {
          phone = this.$store.state.webchat.autoCust[this.sessionId].autoCustPhone || ''
          name = this.$store.state.webchat.autoCust[this.sessionId].autoCustName || ''
          person = this.$store.state.webchat.autoCust[this.sessionId].autoContectPerson || ''
          let autoMatchContent = this.$store.state.webchat.autoCust[this.sessionId].autoMatchContent || ''
          let regPhone = /((\d{11,12})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/gm
          if (autoMatchContent) {
            if (regPhone.test(autoMatchContent)) {
              phone = autoMatchContent
            } else {
              name = autoMatchContent
            }
          }
        }
        var custByAuto = {name: name, phone: [{area: '', memo: person, tel: phone}]}

        return noCustomer ? {...custByAuto} : currCustomer
      },
      urlTabType () {
        let arr = this.$route.path.split('/')
        return arr[3]
      },
      nowTime () {
        return this.$store.state.webchat.nowTimeDiff || 0
      },
      webchatUserHistory () {
        if (this.tabType === 'webchat_todo' && this.$store.state.webchat.current.webchat_todo.messageList[this.sessionId]) {
          return this.$store.state.webchat.current.webchat_todo.messageList[this.sessionId]
        } else if (this.tabType === 'webchat_all' && this.$store.state.webchat.current.webchat_all.messageList) {
          return this.$store.state.webchat.current.webchat_all.messageList
        } else if (this.tabType === 'webchat_robot' && this.$store.state.webchat.current.webchat_robot.messageList) {
          return this.$store.state.webchat.current.webchat_robot.messageList
        } else if (this.tabType === 'webchat_laterProcess' && this.$store.state.webchat.current.webchat_laterProcess.messageList) {
          return this.$store.state.webchat.current.webchat_laterProcess.messageList
        } else {
          return []
        }
      },
      currentCustomer () {
        if (this.tabType && this.$store.state.webchat.current[this.tabType]) {
          return this.$store.state.webchat.current[this.tabType].currentCustomer || {}
        } else {
          return {}
        }
      },
      beInvitedCon () {
        // 是否被三方会话邀请
        return this.$store.state.inviteCon || false
      },
      inviteCon () {
        //  邀请座席信息的box的展示
        if (this.tabType === 'webchat_todo' && this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId]) {
          return this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId].inviteCon
        } else if (this.tabType === 'webchat_all') {
          return false
        } else {
          return false
        }
      },
      inviteConData () {
        // 邀请座席的内容
        if (this.tabType === 'webchat_todo' && this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId].inviteConData) {
          return this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId].inviteConData
        } else if (this.tabType === 'webchat_all') {
          return false
        } else {
          return false
        }
      },
      chatInfo () {
        let messageObj
        if (this.tabType === 'webchat_todo' && this.$store.state.webchat.current.webchat_todo.chatInfoById[this.sessionId]) {
          messageObj = deepClone(this.$store.state.webchat.current.webchat_todo.chatInfoById[this.sessionId])
        } else if (this.tabType === 'webchat_all' && this.$store.state.webchat.current.webchat_all.chatInfoById) {
          messageObj = deepClone(this.$store.state.webchat.current.webchat_all.chatInfoById)
        } else if (this.tabType === 'webchat_robot' && this.$store.state.webchat.current.webchat_robot.chatInfoById) {
          messageObj = deepClone(this.$store.state.webchat.current.webchat_robot.chatInfoById)
        } else if (this.tabType === 'webchat_laterProcess' && this.$store.state.webchat.current.webchat_laterProcess.chatInfoById) {
          messageObj = deepClone(this.$store.state.webchat.current.webchat_laterProcess.chatInfoById)
        } else {
          return {}
        }
        if (typeof messageObj === 'object') {
          if (messageObj.finishKey) {
            messageObj.finishReason = this.finishOptions[messageObj.finishKey] || messageObj.finishReason
          }
          if (messageObj.user && messageObj.user !== 'system' && messageObj.user !== 'robot') {
            let agent = getCache('agents', messageObj.user)
            if (agent.im_icon) {
              messageObj.im_src = agent.im_icon + '?imageView2/1/w/50/h/50'
              if (messageObj.contentType === 'video') {
                messageObj.im_src = agent.im_icon + '?imageView2/1/w/50/h/50'
              }
            } else {
              messageObj.im_src = ''
            }
          } else if (messageObj.user === 'robot') {
            messageObj.im_src = 'robot'
          }
        }
        return messageObj
      },
      webchatData () {
        //  会话的详细信息
        if (this.tabType === 'webchat_todo' && this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId]) {
          return this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId]
        } else if (this.tabType === 'webchat_all' && this.$store.state.webchat.current.webchat_all.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_all.currentSession)
        } else if (this.tabType === 'webchat_robot' && this.$store.state.webchat.current.webchat_robot.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_robot.currentSession)
        } else if (this.tabType === 'webchat_laterProcess' && this.$store.state.webchat.current.webchat_laterProcess.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_laterProcess.currentSession)
        } else {
          return {}
        }
      },
      isVideoing () {
        return this.$store.state.webchat.isVideoing
      },
      isInviteVideo () {
        return this.$store.state.webchat.isinviteVideo
      },
      videoSessionid () {
        return this.$store.state.webchat.videoChatData.videoSessionid
      },
      isScreenShareing () {
        return this.$store.state.webchat.isShareScreening
      },
      screenShareSessionId () {
        return this.$store.state.webchat.shareScreenSessionid
      }
      // ,
      // refreshWebchatRight () {
      //   return this.$store.state.webchat.current.refreshWebchatRight || 0
      // }
    },
    beforeMount () {
      this.$nextTick(() => {
        let arr = this.$route.path.split('/')
        if (arr[3] === 'webchat_todo') {
          if (arr.length > 4) {
            let list = this.$store.state.webchat.webchatList.webchat_todo.list
            if (list.length) {
              let flag = false
              for (let i = 0; i < list.length; i++) {
                if (list[i]._id === arr[4]) {
                  flag = true
                }
              }
              if (flag) {
                this.fetchData()
              } else {
                this.$store.commit('BLANK', 'webchat_todo')
                this.$router.push('/index/webchat/webchat_todo')
              }
            } else {
              this.$store.commit('BLANK', 'webchat_todo')
              this.$router.push('/index/webchat/webchat_todo')
            }
          } else {
            this.$store.commit('BLANK', 'webchat_todo')
            this.$router.push('/index/webchat/webchat_todo')
          }
        } else {
          this.fetchData()
        }
      })
      // bus.$on('updateImageUrls', (data) => {
      //   // 更新msgbox里计算出来的图片地址数组
      //   this.imageUrls = data
      // })
    },
    mounted () {
      let self = this
      let timer
      bus.$on('renderWebchatContainer', (msg) => {
        self.initData()
        clearTimeout(timer)
        timer = setTimeout(() => {
          self.renderCustomer = true
          console.log('==========客户组件加载完成????==========')
        }, 500)
      })
      bus.$on('quickReplyCopy', (msg, flag) => {
        if (flag) return
        let str = this.sendChatMsg.content
        this.sendChatMsg.content = str + msg
        document.querySelectorAll('.send_msg_textarea')[0].focus()
      })
    },
    beforeDestroy () {
      bus.$off('renderWebchatContainer')
      bus.$off('quickReplyCopy')
      document.removeEventListener('click', this.showSuggestMethods)
    },
    methods: {
      videoReplay1 (data) {
        this.playVideoReplay = true
        this.videoReplayUrl = data.url
        this.videoReplatChatMsg = data.ChatMsg
      },
      closeVideoReplay () {
        this.playVideoReplay = false
        this.videoReplayUrl = ''
      },
      closeBigImage () {
        this.webchatBigImage = false
        this.bigImgUrl = ''
      },
      renderWebchatContainer () {
        bus.$emit('renderWebchatContainer', 'renderWebchatContainer is change')
        bus.$emit('changeCusComponents')  // 更新添加客户组件
        bus.$emit('changeCusSource')  // 更新客户的来源
        bus.$emit('changeCusStatus')  // 更新客户的状态
        bus.$emit('changeCusOwner')  // 更新客户的归属
        bus.$emit('changeCascader')  // 更新级联选项事件
      },
      fetchData () {
        console.log('Summary fetchData')
        this.loading = true
        this.cardLoading = true
        let type = this.type
        if (type !== 'webchat' || this.path.length <= 3) {
          this.cardLoading = false
          this.renderWebchatContainer()
          // this.$store.commit(types.RENDER_WEBCHAT_CONTAINER, Math.random()) // 去掉v-if后加载在线咨询右侧详情
          this.loading = false
          return
        }
        let webchatList = this.$store.state.webchat.webchatList[this.tabType].list
        let flag = true
        if (this.path.length > 4) {
          webchatList.forEach((item) => {
            if (item._id === this.callId) {
              flag = false
            }
          })
        }
        if (flag) {
          this.loading = false
          this.cardLoading = false
          this.renderWebchatContainer()
          return
        }
        let _id = this.callId
        this.sessionId = _id
        this.$emit('routeChange', this.tabType)
        let sid = ''
        let self = this
        // 翻页后该数据获取不到
        this.$store.state[type][type + 'List'][this.tabType].list.forEach(function (data) {
          if (data._id === _id) {
            sid = data.sid || ''
            self.sid = data.sid
            self.customerId = data.custId || ''
          }
        })
        let dealMsgFlag = false
        if (this.tabType === 'webchat_todo') {
          let currentSession = this.$store.state.webchat.current[this.tabType].currentSession[_id]
          let currentHistory = this.$store.state.webchat.current[this.tabType].messageList[_id]
          this.$store.state.webchat.webchatList.webchat_todo.list.forEach((item) => {
            if (item._id === this.sessionId && item.leakNum > 0) {
              dealMsgFlag = true
            }
          })
          if (currentSession && currentHistory) {
            // 切换后重新赋值webchat_todo下面的currentCustomer
            this.$store.commit(gtypes.SET_CURRENT_CUSTOMER, {data: this.$store.state.webchat.current[this.tabType].currentSession[_id].currentCustomer, type: 'webchat', tabType: 'webchat_todo', businessId: _id})
            this.cardLoading = false
            this.renderWebchatContainer()
            this.$store.commit(types.QUERY_WEBCHAT_CURRENT_SESSION, {_id: _id, tabType: this.tabType})
            this.sid = this.$store.state.webchat.current[this.tabType].currentSession[this.sessionId].sid || ''
            if (dealMsgFlag) {
              dealWebchatMsg(this.$store, {_id: _id, sid: sid, tabType: this.tabType}) // 会话未读数更新
            }
            this.loading = false
            return
          }
        }

        let importSid = ''
        if (this.$store.state.webchat.autoCust[_id]) {
          importSid = this.$store.state.webchat.autoCust[_id].importSid || ''
        }
        let info = {
          autoCustName: '',
          autoCustPhone: '',
          autoMatchContent: '',
          autoMatchType: '',
          autoCustLength: -1,
          autoCustObj: {},
          importSid: importSid
        }
        this.$store.commit('webchat/INIT_WEBCHAT_MESSAGELIST_SESSION', {sessionId: _id, tabType: this.tabType})
        this.$store.commit('webchat/AUTO_CUST_INFO', {sessionId: _id, data: info})
        const f1 = getWebchatDetail(this.$store, _id, sid, this.tabType)
        const f2 = getChatInfoById(this.$store, _id, sid, this.tabType)
        let that = this
        Promise.all([f1, f2]).then(function () {
          if (that.tabType === 'webchat_todo' && that.$store.state.webchat.current[that.tabType].chatInfoById[_id]) {
            let chatStatus = that.$store.state.webchat.current[that.tabType].chatInfoById[_id].status || ''
            if (chatStatus === 'changePeer') {
              // 加载会话的时候加载流转信息，但是流转消息的数据欠缺，暂时中止
              let platform = ''
              let sid = ''
              if (that.tabType === 'webchat_todo') {
                platform = that.$store.state.webchat.current[that.tabType].chatInfoById[_id].platform || ''
                sid = that.$store.state.webchat.current[that.tabType].chatInfoById[_id].sid || ''
              } else {
                platform = that.$store.state.webchat.current[that.tabType].chatInfoById.platform || ''
                sid = that.$store.state.webchat.current[that.tabType].chatInfoById.sid || ''
              }
              let data = {
                type: 'out',
                platform: platform,
                sid: sid,
                message: that.$t('webchat.changePeerOther'),
                _id: _id,
                contentType: 'text',
                content: that.$t('webchat.changePeerOther'),
                status: 'changePeer',
                uidDesc: that.$t('public.system')
              }
              that.$store.commit(types.UPDATE_WEBCHAT_MESSAGE_LIST, data)
            }
          }
          that.cardLoading = false
          that.renderWebchatContainer()
          that.loading = false
        }).then(() => {
          if (dealMsgFlag) {
            dealWebchatMsg(this.$store, {_id: _id, sid: sid, tabType: this.tabType}) // 更新会话未读数
          }
        })
      },
      unbundling () {
        this.$confirm(this.$t('public.unlinkCustomerPrompt'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.unbundlingFun()
        }).catch(() => {})
      },
      unbundlingFun () {
        let sName = ''
        let sessionId = this.$route.path.split('/')[4]
        if (this.tabType === 'webchat_todo') {
          sName = this.$store.state.webchat.current[this.tabType].chatInfoById[sessionId].sName
        } else if (this.tabType === 'webchat_all' || this.tabType === 'webchat_robot' || this.tabType === 'webchat_laterProcess') {
          sName = this.$store.state.webchat.current[this.tabType].chatInfoById.sName
        }
        this.$store.dispatch('deleteCustomerImRelation', {customerId: this.customer._id, sessionId: sessionId, sid: this.sid, sName: sName}).then((res) => {
          bus.$emit('changeCusComponents')  // 更新添加客户组件
          bus.$emit('changeCusSource')  // 更新客户的来源
          bus.$emit('changeCusStatus')  // 更新客户的状态
          bus.$emit('changeCusOwner')  // 更新客户的归属
          bus.$emit('changeCascader')  // 更新级联选项事件
        })
      },
      handleExpandLayout (state) {
        this.expandLayout = state
      },
      showVideoTipsDialog (tips) {
        this.VideoTipsDialog = true
        this.VideoActionTips = tips
      },
      cancelInviteSession (data) {
        this.$store.commit(types.CANCEL_WEBCHAT_INVITECONDATA, {sessionId: data.sessionId, value: false})
      },
      endSessionFun () {
        let data = {
          _id: this.webchatData._id,
          sid: this.webchatData.sid,
          finishReason: this.$t('webchat.addBlack'),
          finishKey: 'add_black',
          remark: ''
        }
        this.$store.dispatch('finishWebchatSession', data).then(() => {
          this.$store.commit('BLANK', 'webchat_todo')
          this.$router.replace({path: '/index/webchat/webchat_todo'})
        })
      },
      fetchDataContainer () {
        if (document.querySelectorAll('.send_msg_textarea')[0]) {
          document.querySelectorAll('.send_msg_textarea')[0].focus() // 获取焦点
        }
        if (this.tabType === 'webchat_todo') {
          this.showGrabIcon = false
        } else if (this.tabType === 'webchat_all' || this.tabType === 'webchat_robot' || this.tabType === 'webchat_laterProcess') {
          // 全部中展示浏览信息
          let isContainPeer = false
          let self = this
          this.$store.dispatch('getCache', {type: 'accessChannelAgent', id: this.webchatData.toPeer}).then((peer) => {
            if (peer && peer.agents && peer.agents.length) {
              let accessAgents = []
              accessAgents = peer.agents
              accessAgents.forEach((item) => {
                if (item.agentID === this.$store.state.session.user._id) {
                  isContainPeer = true
                }
              })
            }
            if (!isContainPeer) {
              self.showGrabIcon = false
            } else if (this.$store.state.session.user._id === this.webchatData.user) {
              self.showGrabIcon = false
            } else if (this.webchatData.status !== 'deal') {
              self.showGrabIcon = false
            } else if (!contains(this.$store.state.session.user.funcIds, 'func_webchat_grab')) {
              self.showGrabIcon = false
            } else if (this.webchatData.inviteUserStatus === 'accept') {
              self.showGrabIcon = false
            } else {
              self.showGrabIcon = true
            }
          })
        }
      },
      getAllQuickReplay () {
        let flag = this.$store.state.webchat.current.webchat_todo.allQuickReply.flag
        if (flag) {
          let data = {
            'moduleType': 'webchat'
          }
          this.$store.dispatch('getAllQuickReplyListNew', data)
        }
      },
      customerAddBlack () { // 客户加入黑名单
        this.endSessionFun()
      },
      startVideoChat () {
        if (this.isVideoing || this.isInviteVideo) {
          this.VideoTipsDialog = true
          this.VideoActionTips = this.$t('videoChat.EndExistVideoFirst')
          return
        }
        if (this.isScreenShareing && this.webchatData._id === this.screenShareSessionId) {
          this.VideoTipsDialog = true
          this.VideoActionTips = this.$t('screenShare.EndExistShareFirst')
          return
        }
        let currentWebchat
        let webchatList = this.$store.state.webchat.webchatList.webchat_todo.list
        webchatList.forEach((item) => {
          if (item._id === this.webchatData._id) {
            currentWebchat = item
          }
        })
        if (currentWebchat.userStatus === 'offline') {
          this.VideoTipsDialog = true
          this.VideoActionTips = this.$t('videoChat.ChatOfflineCanNotVideo')
          return
        }
        let msg = {
          currUser: this.webchatData.user,
          sid: this.webchatData.sid,
          sessionId: this.webchatData._id,
          sName: this.webchatData.sName
        }
        this.$store.dispatch('requestVideoChat', msg)
      },
      startShareScreen () {
        if (this.isVideoing || this.isInviteVideo) {
          // 视频中或被视频邀请中
          this.VideoTipsDialog = true
          this.VideoActionTips = this.$t('videoChat.EndExistVideoFirst')
          return
        }
        if (this.isScreenShareing) {
          // 已经在桌面共享过程中了
          this.VideoTipsDialog = true
          this.VideoActionTips = this.$t('screenShare.EndExistShareFirst')
          return
        }
        // 访客离线
        let currentWebchat
        let webchatList = this.$store.state.webchat.webchatList.webchat_todo.list
        webchatList.forEach((item) => {
          if (item._id === this.webchatData._id) {
            currentWebchat = item
          }
        })
        if (currentWebchat.userStatus === 'offline') {
          this.VideoTipsDialog = true
          this.VideoActionTips = this.$t('screenShare.ChatOfflineCanNotShare')
          return
        }
        if (this.inviteCon || this.webchatData.inviteUserStatus === 'accept' || this.beInvitedCon) {
          // 处于三方会话中
          this.$message({
            message: this.$t('screenShare.agent_three_share'),
            type: 'error'
          })
          return
        }
        let msg = {
          status: true,
          id: this.webchatData._id,
          name: this.webchatData.sName
        }
        this.$store.dispatch('changeStatusBeforeShare', {_id: this.webchatData._id, operation: 'confirm', sid: this.webchatData.sid || ''})
        this.$store.commit(types.SET_SHARESCREEN, msg)
      },
      initData () {
        this.fetchDataContainer()
        if (!this.currentCustomer._id) {
          let dataObj = {
            importSid: webchatUtils.getImportSidByPlantform(this.chatInfo.sid, this.chatInfo.platform)
          }
          this.$store.dispatch('getMatchMsgResponse', {data: dataObj, sid: this.sessionId})
        }
        this.chatMsgCon.font = window.localStorage.getItem('imFontCon')
        if (!this.nowTime) {
          let data = new Date()
          let time = data.getTime()
          this.$store.dispatch('getServerTimeDiff', time).then((res) => { // 获取当前时间和服务器的时间差
            if (res.success) {
              this.$store.commit(types.SET_SERVER_TIME_DIFF, res.data)
            }
          })
        }
        if (!this.chatMsgCon.font) { // 没有设置字体大小使用默认的
          this.chatMsgCon.font = 'font12'
        }
        if (this.tabType === 'webchat_todo' && document.getElementsByClassName('send_msg_textarea')) {
          this.getAllQuickReplay()
        }
        if (this.$route.path.split('/').length > 4 && this.$store.state.webchat.lastContent[this.$route.path.split('/')[4]] !== undefined) {
          this.sendChatMsg.content = this.$store.state.webchat.lastContent[this.$route.path.split('/')[4]]
        }
        this.$store.dispatch('getCache', {type: 'channelDic'}).then((res) => {
          for (let i = 0; i < res.length; i++) {
            if (res[i].type === 'webchat') {
              this.finishArr = res[i].options || []
              break
            }
          }
          this.finishOptions = initFinishName(this.finishArr, {})
        })
      },
      // 在线咨询座席主动发起会话
      initiatingWebchat () {
        // cc20.4需求，对接会话支持发起主动会话
        // if (this.chatInfo && this.chatInfo.docking) {
        //   this.$message.error(this.$t('webchat.DockingCannotInitiatingSession'))
        //   return
        // }
        // console.log(this.webchatData)
        this.initiatingSessionBtn = this.$t('webchat.initiatingSessionNow')
        this.$store.dispatch('initiatingWebchat', {chatSessionId: this.webchatData._id, sid: this.webchatData.sid || ''}).then((res) => {
          if (res.success) {
            this.initiatingSessionBtn = this.$t('webchat.initiatingSession')
            let isLeaveMsg = this.webchatData.leavemsg ? true : false
            bus.$emit('initiatingWebchatFun', isLeaveMsg)
            this.$message.success(this.$t('webchat.initiatingSucceess'))
          } else {
            this.initiatingSessionBtn = this.$t('webchat.initiatingSession') // 改变按钮的显示状态
            if (res.message === 'webchat.webchat_not_finish' && res.data) {
              if (res.data.status === 'deal') {
                this.$message.error(this.$t('webchat.initiatingSessionDeal', {agent: res.data.exten}))
              } else if (res.data.status === 'robot') {
                this.$message.error(this.$t('webchat.initiatingSessionRobot'))
              } else if (res.data.status === 'undeal') {
                this.$message.error(this.$t('webchat.initiatingSessionUndeal'))
              } else {
                this.$message.error(this.$t('webchat.initiatingSessionOther'))
              }
            }
          }
        })
      }
    },
    components: {
      videoReplay,
      sendChatMsgBox,
      InviteConversation,
      WebchatConMsgBox,
      WebchatConChatHead,
      WebchatConChatInfo
      // BigImage
    }
  }
  function updateCurrentWebchatList (store, sid, currentCustomer) {
    store.dispatch('updateCurrentWebchatListCustomer', {sid: sid, customer: currentCustomer})
  }
  function getWebchatDetail (store, _id, sid, submenu) {
    let data = {_id: _id, sid: sid, submenu: submenu}
    return store.dispatch('popupWebchat', data)
  }
  function getChatInfoById (store, _id, sid, submenu) {
    let data = {
      cust_id: '',
      queryHistory: true,
      submenu: submenu,
      _id: _id,
      sid: sid
    }
    return store.dispatch('queryChatInfoById', data)
  }
  function dealWebchatMsg (store, data) {
    return store.dispatch('dealMsg', data)
  }
</script>
<style lang="stylus" scoped>
@import "../webchat/style/webchatCon.styl"
</style>